<template>
	<div class="holy-grail-layerout">
		<HeaderMenus class="header" v-if="isShowCfgurator" v-show="!isFullScreen" />
		<div class="body">
			<LayerManager
				class="left-sider"
				v-if="isShowCfgurator"
				v-show="leftPanelVisible"
				:cpnt-nav-tree="props.cpntNavTree" />
			<ComponentContainer
				ref="container"
				id="cpnt-frame-container"
				class="content cpnt-container"
				:cpnt-nav-tree="props.cpntNavTree" />
			<ComponentConfigurator
				class="right-sider"
				v-if="isShowCfgurator"
				v-show="rightPanelVisible"
				:active-cpnt-id-arr="activeCpntIdArr" />
		</div>
		<FooterStatus class="footer" v-if="isShowCfgurator" v-show="!isFullScreen" />
		<div class="fullscreen-exit-btn" v-if="isFullScreen" @click="exitFullScreen">
			<div class="exit-icon"><img :src="exitIcon" /></div>
			<div class="exit-text">退出全屏</div>
		</div>
	</div>
</template>

<script lang="ts" setup>
import {
	onMounted,
	reactive,
	toRefs,
	computed,
	ref,
	// watch,
	onBeforeMount,
	provide,
	inject,
	getCurrentInstance,
	onUpdated
} from 'vue';
import LayerManager from './LayerManager.vue';
import HeaderMenus from './HeaderMenus.vue';
import FooterStatus from './FooterStatus.vue';
import ComponentContainer from './ComponentContainer.vue';
import ComponentConfigurator from '@CIF/ComponentConfigurator/index.vue';
import OverlayScrollbars from 'overlayscrollbars';
import { ComponentTreeHelper } from '@CIF/ComponentTemplate/componentTree';
import _ from 'lodash';
import { usePrimaryStore } from '@/store';
import { RUNTIME_CFG_ENUM } from '@CIF/Runtime/Global/variable';
import Notifier from '@CIF/Utils/Notifier.js';
import exitIcon from '@CIF/Runtime/assets/exit-fullscreen2.svg';
import StorageHelper from '@CIF/Runtime/Global/storage';

const instance = getCurrentInstance();
inject('renderer');
const store = usePrimaryStore();
const props = defineProps({
	// cifMode: {
	// 	type: String,
	// 	default: ''
	// },
	cpntNavTree: {
		type: Array,
		default() {
			return [];
		}
	}
});
const state = reactive({
	// activeCpntIdArr: [], // 当前画布通过点击激活的组件id, 可用于获取当前选中的组件
	overActiveCpntId: '', // 当前画布hover事件激活的组件id
	cpntFlatLayer: [], // 当前应用的激活的组件组件图层, 是一个数组，不包含组件树嵌套结构，维护组件的层级信息，主要用于快速存取利用组件层级
	historyCache: [], // 历史操作数据用于undo redo
	currentHistoryIndex: -1, // redo undo 指针

	copyCpntNavTree: '', // 用于监听去干扰,字符串类型,方便比较
	// keys: {}, // 按键监听记录

	RUNTIME_CFG_ENUM: RUNTIME_CFG_ENUM,
	exitIcon
});
const container = ref();
// watch(
// 	() => props.cpntNavTree,
// 	(newTree) => {
// 		console.log('------------------------------------newTree', newTree);
// 	},
// 	{ deep: true }
// );
const keys = ref<any>({}); // 按键监听记录
const isShowCfgurator = computed(() => {
	if (cifMode.value !== RUNTIME_CFG_ENUM.PRODUCTION_MODE) {
		return true;
	} else {
		return false;
	}
});
const isFullScreen = computed(() => {
	return store.getFullScreenState && isShowCfgurator.value;
});
const activeCpntIdArr = computed(() => {
	return store.getActiveCpntIdArr;
});
const leftPanelVisible = computed(() => {
	if (isFullScreen.value) return false;
	return store.getLeftPanelVisible;
});
const rightPanelVisible = computed(() => {
	if (isFullScreen.value) return false;
	return store.getRightPanelVisible;
});

function exitFullScreen() {
	store.setFullScreenState(false);
}
function unsetActiveCpnt() {
	if (activeCpntIdArr.value.isNull()) return;
	store.setActiveCpntIdArr([]);
}
function setCpntActive(cpnt: any) {
	if (keys.value.ctrl) {
		if (!Array.isArray(activeCpntIdArr.value)) {
			unsetActiveCpnt();
		}
		// this.activeCpntIdArr.push(cpnt.uuid)
		store.setActiveCpntIdArr([...activeCpntIdArr.value, cpnt.uuid]);
	} else {
		store.setActiveCpntIdArr([cpnt.uuid]);
	}
}
const cifMode = ref(StorageHelper.get(RUNTIME_CFG_ENUM.CIF_MODE));
function initCpntFrame() {
	if (_.get(window, 'cif.config.logger.enable', false) === true) {
		console.log(
			'CIF.R.R.ComponentFrame:initCpntFrame 初始化组件渲染器布局视图（默认选中首个组件）'
		);
	}
	if (cifMode.value != RUNTIME_CFG_ENUM.PRODUCTION_MODE) {
		state.cpntFlatLayer = ComponentTreeHelper.getTreeFlatLayer(props.cpntNavTree);
		if (!_.isEmpty(state.cpntFlatLayer)) {
			setCpntActive(state.cpntFlatLayer[0]);
		}
	}
}
function scrollToCpnt(cpntTreeNode: any) {
	const cpntInst = _.get(cpntTreeNode, 'componentInstance', {});
	if (!_.isEmpty(cpntInst)) {
		scrollInst.scroll({ x: cpntInst.left, y: cpntInst.top }, 300);
	}
}

// 右键菜单 有些变量没有定义，待完善
function handleContextMenu(e: any, item: any = {}) {
	// if (!item.uuid) return;
	// if (!this.isSelectActive) {
	// 	store.setActiveCpntIdArr([item.uuid]);
	// }
	// if (keys.value.ctrl) return;
	// nextTick(() => this.$refs.contentmenu.show(e.clientX, e.clientY));
}

onBeforeMount(() => {
	Notifier.listenToChannel(
		'LAYER_MANAGER_TRIGGER_CPNT_LOCATION',
		scrollToCpnt,
		'LAYER_MANAGER_TRIGGER_CPNT_LOCATION_LISTENER'
	);
});
let scrollInst: any;
onMounted(() => {
	if (_.get(window, 'cif.config.logger.enable', false) === true) {
		console.log('CIF.R.R.ComponentFrame:mounted');
	}
	scrollInst = OverlayScrollbars(document.getElementById('cpnt-frame-container'), {
		className: 'os-theme-minimal-light',
		scrollbars: {
			autoHide: 'leave'
		}
	});
	// console.log('===============scrollInst', scrollInst);
});
onUpdated(() => {
	if (_.get(window, 'cif.config.logger.enable', false) === true) {
		console.log('CIF.R.R.ComponentFrame:updated');
	}
});

defineExpose({ ...toRefs(state), initCpntFrame });
provide('cpntFrame', { handleContextMenu, state, container });
</script>

<style lang="scss" scoped>
$headerHeight: 52px; // 48px + 2px margin * 2
$footerHeight: 22px;
$leftSiderwidth: 300px;
$rightSiderwidth: 360px;
.holy-grail-layerout {
	width: 100%;
	height: 100%;
	display: flex;
	flex-direction: column;
	position: relative;
	background: #21222c;
	.body {
		height: calc(100% - $headerHeight - $footerHeight);
		display: flex;
		flex: 1;
		overflow: hidden;

		.left-sider {
			/* 两个边栏的宽度设为12em */
			flex: 0 0 $leftSiderwidth;
			max-width: $leftSiderwidth;
			/* 导航放到最左边 */
			order: -1;
		}

		.left-sider-collapse {
			display: none;
			/* background: white; */
		}

		.content {
			height: 100%;
			width: calc(100% - $leftSiderwidth - $rightSiderwidth);
			flex: 1;
			/* background: red; */
			/* overflow: scroll; */
			background-color: #121212;
		}

		.cpnt-container {
			z-index: 2;
		}

		.right-sider {
			/* position: relative;
      top: 0;
      right: 0; */

			/* 两个边栏的宽度设为12em */
			flex: 0 0 $rightSiderwidth;
			max-width: $rightSiderwidth;
			/* background: purple; */
		}

		.right-sider-collapse {
			display: none;
		}
	}
	.footer {
		flex: 0 0 $footerHeight;
		z-index: 2;
	}
	.fullscreen-exit-btn {
		z-index: 999;
		position: fixed;
		padding: 0 4px;
		bottom: 100px;
		right: -72px;
		display: flex;
		height: 28px;
		line-height: 29px;
		text-align: left;
		font-size: 16px;
		font-weight: 700;
		width: 92px;
		background-color: var(--dropdown-background);
		border: solid 2px var(--primary-hover);
		border-left: solid 4px var(--primary);
		border-radius: 4px;
		transition: all 0.2s cubic-bezier(0.075, 0.82, 0.165, 1);
		color: var(--white);
		box-sizing: content-box;
		cursor: pointer;

		.exit-icon {
			margin-right: 6px;
			height: 28px;
			line-height: 28px;
			width: 22px;

			img {
				width: 100%;
				height: 100%;
			}
		}

		.exit-text {
			flex: 1;
		}

		&:hover {
			transform: translateX(-68px);
		}
	}
}
</style>
